type PageType = 1 | 2;
interface RouterProps {
  name: string;
  path: string;
  redirect?: string;
  component?: any;
  meta: {
    title?: string; // 菜单名称
    visible?: boolean; // 是否显示在菜单栏
    icon?: boolean; // 菜单icon
    page_type?: PageType; // 页面类型 1:layout 2:page
    keepAlive?: boolean; // 是否需要缓存
    isOpenNewWindow?: boolean; // 是否是新窗口打开
  };
  children?: RouterProps[];
}
import BasicLayout from "@layout/index";
import { overviewRoute, rootRoute } from "@/routes/config";
import { openNewWindowMap } from "./window";
const redirectMap = {};
Object.keys(openNewWindowMap).forEach((path) => {
  const $name = DiagonalToHorizontal(path, true);
  redirectMap[path] = {
    path: rootRoute + $name,
    name: $name,
    meta: {
      visible: false,
      page_type: 1,
    },
  };
});
const redirectRoutes: RouterProps[] = [];
export const getComponentName = (path: string) =>
  path?.replace?.(/\//g, "-")?.replace(/^-/, "");
const importMap: Map<string, any> = new Map();
(() => {
  nextTick(() => {
    const modules: any = import.meta.glob(
      [
        "@/views/*/*/index.tsx",
        "@/views/*/*/index.vue",
        "@/views/*/index.tsx",
        "@/views/*/index.vue",
      ],
      {
        eager: true,
      }
    );
    Object.keys(modules).forEach((key: any) => {
      const path = key
        ?.replace("/src/views", "")
        ?.replace(/\/index\.(vue|jsx|tsx)/, "");
      modules[key].default.name = getComponentName(path);
      importMap.set(path, modules[key]?.default);
    });
  });
})();

const defaultRoutes: any = ["/overview"];
const importModuleComponent = (path) => {
  const key = path?.replace?.(/^[^\/]/, (match) => "/" + match);
  if (importMap.has(key)) return importMap.get(key);
  return () => import("@/views/404");
};
const importComponent = (path: string, page_type = 1) => {
  if (page_type === 0) return BasicLayout;
  if (page_type === 1 && defaultRoutes.includes(path)) return BasicLayout;
  return importModuleComponent(path);
};
const generateRouter = (routes: RouterProps[]) => {
  return routes.map((route) => {
    const { name, path, redirect, meta = {}, children } = route;
    const $name = getComponentName(path);
    const $component = importComponent(path, meta.page_type);
    const $meta = {
      ...meta,
      isOpenNewWindow: openNewWindowMap[path],
    };
    if (redirectMap[path]) {
      redirectRoutes.push({
        ...redirectMap[path],
        component: $component,
      });
      return {
        name: $name,
        path,
        redirect: redirectMap[path].path,
        meta: $meta,
      };
    }
    const newRoute: RouterProps = {
      name: $name,
      path,
      component: $component,
      meta: $meta,
    };
    if (
      meta.page_type === 1 &&
      defaultRoutes.includes(path) &&
      !children?.length
    ) {
      const $component = importModuleComponent(path);
      newRoute.path = rootRoute;
      newRoute.children = [
        {
          name: $name,
          path,
          component: $component,
          meta: $meta,
        },
      ];
      return newRoute;
    }
    if (children && children.length > 0)
      newRoute.children = generateRouter(children);
    return newRoute;
  });
};
export const isRegisterRouter = ref(false);
export const set_isRegisterRouter = (value: boolean) =>
  (isRegisterRouter.value = value);
const removeRouteList: any[] = [];
export const clearAllRegisteredRouter = () => {
  removeRouteList.forEach((removeRoute) => removeRoute?.());
  set_isRegisterRouter(false);
};

export const registerAllRouter = (router, routes) => {
  const newRoutes = generateRouter(routes);
  newRoutes.forEach((route) => {
    try {
      const removeRoute = router.addRoute(route);
      if (route.path != overviewRoute.path) removeRouteList.push(removeRoute);
    } catch (e) {
      console.error(`路由格式错误: ${e}`);
    }
  });
  redirectRoutes.forEach((route) => {
    const removeRoute = router.addRoute(route);
    removeRouteList.push(removeRoute);
  });
  set_isRegisterRouter(true);
};
export default (router: any, routes: RouterProps[]) => {
  if (isRegisterRouter.value) return true;
  registerAllRouter(router, routes);
  return false;
};
